<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <script>	
      function chainRequest(commands) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(data) {
          if (xhr.readyState == 4) {
            // if (xhr.status == 200) {
              if (commands.length > 1)
                window.setTimeout(function() { 
                        chainRequest(commands.slice(1)) }, 750);
            // } else {
              // abort!
            // }
          }
        }

        var ip = localStorage['ip'];
        var url = 'http://' + ip + ':8060/' + commands[0];
        xhr.open('POST', url, true);
        xhr.send();
      };
      
      chrome.extension.onRequest.addListener(
        function(request, sender, callback) {
	        switch (request.name){

		      case "getPrefs":
		          // request from the content script to get the preferences.
              	callback(
                    {
                       appId : localStorage["appId"],
                       ip : localStorage['ip']
                    });
            	break;

              case "setPrefs":
            	localStorage['ip'] = request.rokuIp;
            	localStorage['appId'] = request.appId;
            	break;

              case "launch":
            	var appId = localStorage['appId'];
            	var ip = localStorage['ip'];
  		        chainRequest([ 'launch/' + appId + '?trackIDs=' + request.trackIds.join(' ') ]);
			    break;
		   }
        }
      );
      </script>
  </body>
</html>